#include "BondDetailData.h"
#include "../BondUtility.h"
#include <list>

void DetailData::onBestPriceArrived(std::string strKey, QList<xQBBestPriceUnit_c> lstBestPrice)
{
	if (strKey != m_combondKey)
		return;

	xQBMarketStreamUnit_c unit;
	std::list<std::string> lstBroker;

	QList<int> flashIds;
	std::map<std::string, int> bestPriceChanged;
	for (auto iter = lstBestPrice.begin(); iter != lstBestPrice.end(); ++iter)
	{
		BondUtility::transfBestPriceToMarketStream(*iter, unit);

		bool checkSettlementOK = true;
		if (m_clearSpeed > 0)
			checkSettlementOK = BondUtility::updateMarketStreamBySettlement(unit, m_clearSpeed, true, false);

		if (m_mapMktStream.empty())
		{
			unit.m_indexID = 1;
			m_mapMktStream[1] = unit;
			flashIds.push_back(1);
		}
		else
		{
			auto itm = m_mapMktStream.rbegin();
			bool exist = false;
			unit.m_indexID = itm->second.m_indexID + 1;
			for (int i = 0; i < 30 && itm != m_mapMktStream.rend(); ++i, ++itm)
			{
				if (itm->second.isSameMarketStream(unit))//TODO: cfets
				{
					exist = true;
					break;
				}
			}
			if(exist)
				continue;
			m_mapMktStream[unit.m_indexID] = unit;
			flashIds.push_back(unit.m_indexID);
		}
		lstBroker.push_back(iter->m_company_id);

		if (checkSettlementOK)
		{
			if (strcmp(iter->m_symbol, "1") == 0)//bid
				bestPriceChanged[iter->m_company_id] |= 1;
			else if (strcmp(iter->m_symbol, "-1") == 0)//ofr
				bestPriceChanged[iter->m_company_id] |= 2;
		}
	}

	emit marketStreamChanged(flashIds);
	emit brokerBestPriceChanged(bestPriceChanged);
}
